package com.epalmpay.service.group.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import com.epalmpay.entity.*;
import com.epalmpay.mapper.*;
import com.epalmpay.payplat.IPayAPI;
import com.epalmpay.payplat.PayUserAccounts;
import com.epalmpay.payplat.result.PayResult;
import com.epalmpay.util.*;
import com.epalmpay.util.Response;
import com.epalmpay.util.payplat.DateUtils;
import com.epalmpay.util.payplat.UtilFun;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.epalmpay.exception.ApplicationException;
import com.epalmpay.status.Rescode;
import com.epalmpay.dto.merchantmanage.GroupInDTO;
import com.epalmpay.dto.merchantmanage.GroupListOutDTO;
import com.epalmpay.dto.merchantmanage.GroupOutDTO;
import com.epalmpay.dto.merchantmanage.GroupPayconfigInDTO;
import com.epalmpay.dto.merchantmanage.GroupPayconfigOutDTO;
import com.epalmpay.dto.merchantmanage.GroupWxconfigInDTO;
import com.epalmpay.dto.merchantmanage.GroupWxmenuInfoInDTO;
import com.epalmpay.dto.merchantmanage.GroupWxmenuInfoOutDTO;
import com.epalmpay.dto.merchantmanage.GroupWxtemplateInDTO;
import com.epalmpay.dto.merchantmanage.GroupWxtemplateListOutDTO;
import com.epalmpay.dto.merchantmanage.GroupWxtemplateOutDTO;
import com.epalmpay.dto.system.BaseOutDTO;
import com.epalmpay.dto.system.UserInDTO;
import com.epalmpay.enumdef.BizEnum.SMSTemplateType;
import com.epalmpay.enumdef.BizEnum.UserStatus;
import com.epalmpay.enumdef.BizEnum.WebTemplateType;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.enumdef.CommonEnum;
import com.epalmpay.service.group.IGroupService;
import com.epalmpay.service.weixin.IWxBaseService;
import com.epalmpay.service.weixin.impl.WxService;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.common.exception.WxErrorException;


@Service("groupService")
public class GroupServiceImpl implements IGroupService {
	
	@Resource  
    private GroupMapper groupMapper;
	@Resource  
	private UserbaseMapper userbaseMapper;
	@Resource
    private ModuleMapper moduleMapper;
	@Resource
    private GroupModuleMapper groupModuleMapper;
	@Resource 
	private GroupWxconfigMapper groupWxconfigMapper;
	@Resource 
	private StatisGroupMapper statisGroupMapper;
	@Resource 
	private GroupConfigMapper groupConfigMapper;
	@Resource 
	private GroupAccountMapper groupAccountMapper;
	@Resource 
	private MemberGradeMapper memberGradeMapper;
	@Resource 
	private GroupWxtemplateMapper groupWxtemplateMapper;
	@Autowired
    protected WxService wxService;
	@Autowired
    protected IWxBaseService wxBaseService;
	@Resource 
	private GroupPayconfigMapper groupPayconfigMapper;
	
	@Resource 
	private GroupWxmenuInfoMapper groupWxmenuInfoMapper;
	@Resource 
	private GroupWxmenuRecordMapper groupWxmenuRecordMapper;
	@Resource
	private AgentMapper agentMapper;
	@Resource
	private GroupProfileMapper groupProfileMapper;
	@Resource
	private GroupPosterMapper groupPosterMapper;

	@Resource
	private AgentRateMapper agentRateMapper;

	@Resource
	private TradeOfflineMapper tradeOfflineMapper;



	
	 @Value("${wqPlateUrl}") String wqPlateUrl;
	
	public List<GroupOutDTO> getGroupList(Integer industryID,
			Integer developeUserID,Date joinStart,Date joinEnd,String name,Page page) throws Exception{
		
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("industryID", industryID);
		param.put("developeUserID", developeUserID);
		param.put("joinStart", joinStart);
		param.put("joinEnd", joinEnd);
		param.put("name", name);
		
		List<GroupOutDTO> result = new ArrayList<GroupOutDTO>();

		int sumCount = groupMapper.selectGroupListCount(param);
		page.setTotalResult(sumCount);
		if(sumCount<=0)
			return null;
		
		param.put("limit", page.getShowCount());
		param.put("start", page.getShowCount()*(page.getCurrentPage()-1));
		
		List<Map<String,Object>> groupList = groupMapper.selectGroupList(param);
		
		
		for (Map<String, Object> group : groupList) {
			GroupOutDTO groupOutDTO = new GroupOutDTO();
			groupOutDTO.setGroupId(SysUtils.Object2Long(group.get("group_id")));
			groupOutDTO.setMerchantName((String)group.get("merchant_name"));
			groupOutDTO.setPayGroupCode((String)group.get("pay_group_code"));
			groupOutDTO.setIndustryID(SysUtils.Object2Long(group.get("industry")));
			groupOutDTO.setIndustryName((String)group.get("industry_name"));
			groupOutDTO.setJoinDate((Date)group.get("gmt_create"));
			groupOutDTO.setDevelopeUserID(SysUtils.Object2Long(group.get("develope_userid")));
			groupOutDTO.setDevelopeUserName((String)group.get("username"));
			groupOutDTO.setMemberNum(SysUtils.Object2Long(group.get("member_num")));
			groupOutDTO.setTradeSumAmount(SysUtils.Object2Long(group.get("trade_sum_amount")));
			groupOutDTO.setIncomeSumAmount(SysUtils.Object2Long(group.get("income_sum_amount")));
			long webChatCount = (Long) group.get("webchat_config");
            groupOutDTO.setIsWebChatConnect(webChatCount>0?Boolean.TRUE:Boolean.FALSE);
            //
            if(group.get("wq_username")!=null&& group.get("wq_password")!=null){
            	
            	 groupOutDTO.setWqPlateUrl(String.format(wqPlateUrl, group.get("wq_username"),group.get("wq_password")));
            }
           
			result.add(groupOutDTO);
		}
		
		return result;
	}
	
	/**新增大商户
	 * @param groupInDTO
	 * @throws Exception
	 */
	@Override
	public Long saveGroup(GroupInDTO groupInDTO)throws Exception{
		
	//	Group groupMax=groupMapper.findMaxId();
		Group group = new Group();
		//取主键id最大值 加1作为主键id保存至数据库
	//	Long groupId=groupMax.getId()+1;
	//	group.setId(groupId); 
		PropertyCopyUtil.copyPropertiesExclude(groupInDTO,group);
		group.setStatus(0);//启用
		group.setGmtCreate(new Date()); 
		group.setGmtModified(new Date()); 
		groupMapper.insert(group);
		//保存大商户统计记录
		StatisGroup statisGroup=new StatisGroup();
		statisGroup.setGmtCreate(new Date());
		statisGroup.setGmtModified(null); 
		statisGroup.setGroupId(group.getId()); 
		statisGroup.setAgentNum(0); 
		statisGroup.setShopNum(0); 
		statisGroup.setMemberNum(0);
		statisGroup.setDeviceNum(0);
		statisGroup.setPosNum(0);
		statisGroup.setScanNum(0);
		statisGroup.setDeskcardNum(0);
		statisGroup.setTradeSumAmount(0L);
		statisGroup.setIncomeSumAmount(0L);
		statisGroup.setThisMemberNum(0);;
		statisGroup.setThisAgentNum(0);
		statisGroup.setThisShopNum(0);
		statisGroup.setTradeSumAmount(0L);
		statisGroup.setThisIncomeAmount(0L);
		statisGroupMapper.insert(statisGroup);
		//保存大商户同时需要同时保存用户名以及密码 同时初始化  模块默认设置为必须选择的值 保存至商户模块中间表当中
		Userbase user=new Userbase();
		user.setUsername(groupInDTO.getUsername()); 
		user.setPassword(new SimpleHash("SHA-1", groupInDTO.getUsername(), groupInDTO.getPassword()).toString());
		user.setBz("admin创建大商户");
		user.setGmtCreate(new Date());
		user.setGmtModified(new Date());
		user.setGroupId(group.getId());
		user.setIp(null);
		user.setLastLogin(null);
		user.setRights(null);//权限码默认为空
		user.setRoleId("");//默认设置为角色管理组
		user.setSkin("default");
		user.setStatus(UserStatus.Normal.getType());
		user.setUserType(CommonEnum.UserType.BusinessManager.getType());
		user.setRoleId("1");
		userbaseMapper.insert(user);
		List<Module> modulelist=moduleMapper.selectDefalutSelected();
		for (Module module : modulelist) {
			GroupModule groupModule=new GroupModule();
			groupModule.setGmtCreate(new Date());
			groupModule.setGmtModified(null);
			groupModule.setGroupId( new Long(group.getId()).intValue());
			groupModule.setModuleId((byte)module.getId().intValue());
			groupModuleMapper.insert(groupModule);
		}
		//创建会员等级  
		MemberGrade memberGrade=new MemberGrade();
		memberGrade.setCanDevelopeMember(true);
		memberGrade.setCanWithdraw(true);
		memberGrade.setDiscountRate(100);//默认折扣比例 100
		memberGrade.setGmtCreate(new Date());
		memberGrade.setGmtModified(new Date());
		memberGrade.setGradeRateId("1");//等级费率id
//		memberGrade.setName("默认等级");
//		memberGrade.setGradeRateId(1L);//等级费率id
		memberGrade.setIcon("");
		memberGrade.setMerchantId(group.getId());
		memberGrade.setName(BizEnum.MemberGradeDefault.attention.getName());
		memberGrade.setNeedAudit(true);
		memberGrade.setUpdateAmount(0); 
		memberGrade.setWalletCanConsume(true);
		memberGrade.setWalletCanReceive(true);
		memberGrade.setWalletCanRecharge(false);
		memberGrade.setWalletCanTransfer(true);
		MemberGrade memberGrade1=new MemberGrade();
		memberGrade1.setCanDevelopeMember(true);
		memberGrade1.setCanWithdraw(true);
		memberGrade1.setDiscountRate(100);
		memberGrade1.setGmtCreate(new Date());
		memberGrade1.setGmtModified(new Date());
		memberGrade1.setGradeRateId("1");//等级费率id
//		memberGrade1.setGradeRateId(1L);//等级费率id
//		memberGrade1.setName("默认等级");
		memberGrade1.setIcon("");
		memberGrade1.setMerchantId(group.getId());//大商户id
		memberGrade1.setName(BizEnum.MemberGradeDefault.unattention.getName());
		memberGrade1.setNeedAudit(false);
		memberGrade1.setUpdateAmount(0); 
		memberGrade1.setWalletCanConsume(true);
		memberGrade1.setWalletCanReceive(true);
		memberGrade1.setWalletCanRecharge(true);
		memberGrade1.setWalletCanTransfer(true);
		memberGradeMapper.insert(memberGrade);
		memberGradeMapper.insert(memberGrade1);
		//创建营销账户   
		GroupAccount groupAccount=new GroupAccount();
		groupAccount.setAccountType(1);//1表示营销账户,2表示真实资金账户
		groupAccount.setBalance(0);
		groupAccount.setBalanceEnc("");
		groupAccount.setGmtCreate(new Date());
		groupAccount.setGmtModified(new Date());
		groupAccount.setGroupId(group.getId());
		groupAccount.setLockAmoountEnc("");
		groupAccount.setLockAmount(0);
		groupAccountMapper.insert(groupAccount);

		//创建分润比例

		GroupProfile groupProfile = new GroupProfile();
		groupProfile.setGmtCreate(new Date());
		groupProfile.setGmtModified(new Date());
		groupProfile.setGroupId(group.getId());
		groupProfile.setZhangfuProfilerate(groupInDTO.getZhangfuProfilerate());
		groupProfile.setPlatformProfilerate(0);
		groupProfile.setExtendProfilerate(0);
		groupProfile.setServiceProfilerate(groupInDTO.getServiceProfilerate());
		groupProfile.setRechargeProfilerate(groupInDTO.getRechargeProfilerate());
		groupProfile.setOperateType(groupInDTO.getOperateType());
		groupProfileMapper.insertSelective(groupProfile);



		//创建第一个掌富账号
		Group group2 = groupMapper.selectByPrimaryKey(group.getId());
		String GroupId = group2.getPayGroupCode();
//		String CustomerName = groupInDTO.getPrincipal();//姓名
		String CustomerName = "卢斌";//姓名


		String MobilePhone = "17717486056";
//		String MobilePhone = groupInDTO.getPrincipalMobile();
		String OrgTranDateTime = DateUtils.getDateTimeString("yyyyMMddHHmmss");
		// 生成UserBase
		String PayPwd = "111111";
		Userbase userbase = new Userbase();
		userbase.setGmtCreate(new Date());
		userbase.setGmtModified(new Date());

		String loginName= StringUtil.getRandNumberStr(9)+"@epalmpay.cn";

		userbase.setUsername(loginName);
		userbase.setPassword(new SimpleHash("SHA-1", loginName, PayPwd).toString());
		userbase.setUserType(CommonEnum.UserType.Agents.getType());
		userbase.setStatus(UserStatus.Stop.getType());
		userbase.setGroupId(group.getId());
		userbase.setRoleId("1");
		userbaseMapper.insertKey(userbase);


		Agent agent  = new Agent();

		agent.setAddressProvince("上海市");
		agent.setAddressCity("上海市");
		agent.setAddressDistrict("浦东新区");
		agent.setMemo("掌富代理");
		agent.setBorcName("掌富代理");
		agent.setLegalPersonIdurl("http://file.ebank007.com/file/sbs_test/group/addGroup/1522200863084[C@62849ff7.jpg");
		agent.setBusinessLicense("123456");
		agent.setLicensePicurl("http://file.ebank007.com/file/sbs_test/group/addGroup/1522200863084[C@62849ff7.jpg");
		agent.setRecieveName("卢斌");
		agent.setRecieveAccountNo("216180100100068521");

//		Map<String, String> mapCardNum = IPayAPI.queryCardCodeNew("216180100100068521");
//		if (!mapCardNum.get("Rcd").equals("0000")) {
//			throw new ApplicationException("该卡暂不支持快捷绑定,请换张卡再试");
//		}
//		mapCardNum.get("InsCd");//行号
		agent.setRecieveBank("0803090000");

		agent.setAgentType((byte)1);
		agent.setPrincipal("卢斌");
		agent.setPrincipalMobile("17717486056");
		agent.setLegalPersonName("卢斌");
		agent.setLegalPersonId("110108196902095811 ");
		agent.setMerchantName("默认代理一"+group.getId());
		agent.setUserId(userbase.getId());
		agent.setGmtCreate(new Date());
		agent.setCreator(groupInDTO.getMerchantName());
		agent.setPacketStatus(true);
		agent.setPayPassword(PayPwd);
		agent.setGroupId(group.getId());
		/*** 当前添加的用角色为渠道或者渠道的管理员**/
		agent.setPrePurchaseMoney(0);
		String UserId = GroupId + UtilFun.formatNumber(agent.getUserId(), 10);
		String PwdAnswer = "000000";
		String PwdQuest = "000000";
//		String Email = agentInfoInDTO.getUsername();
		String Email = loginName;
//		String priOrpub = agent.getRecieveAccountType() == 1 ? "22" : "11";
		String priOrpub = "22";

				//大商户创建
		agent.setAgentLevel(1);
		agent.setParentId(null);
		String merchantCode = agentMapper.selectMaxMerchantCode(null, 5);
		if (StringUtils.isBlank(merchantCode)) {
			//为空 从00001开始计算
			agent.setMerchantCode("00001");
		} else {
			int merCode = Integer.parseInt(merchantCode, 10);
			String merchantCode_ = String.format("%05d", merCode+1);
			agent.setMerchantCode(merchantCode_);
		}

		String SysTraceNum = UtilFun.createRandomNum(10);
		String OrgOrderNum = DateUtils.getDateTimeString("yyyyMMddHHmmsss", new Date())+UtilFun.createRandomNum(5);
//		String CardNum = agentInfoInDTO.getRecieveAccountNo();
		String CardNum = "110108196902095811 ";
//		String issuerId = BizEnum.WithdrawBankList.fromType("360281199209198014").getName();
		agent.setAgentStatus(Byte.valueOf(BizEnum.AgentStatus.Stop.getType()+""));
		agent.setSource(BizEnum.AgentSource.Inside.getType());
		agent.setPacketStatus(true);
		agent.setPacketNum(UserId);
		agent.setSort(0);

		agent.setPrePurchaseStatus(0);
		agent.setRecommendUrl(null);
		agent.setRecommendLink(null);

		//身份证
		String CertNo =null;
		String cardIntegral = "000000000000";
		if (StringUtils.isNotBlank("110108196902095811")) {
//		if (StringUtils.isNotBlank(agentInfoInDTO.getBankBranch())) {
			CertNo = "110108196902095811";
			agent.setBankBranch(CertNo);
		}else{
			CertNo = "110108196902095811";
//			CertNo = agentInfoInDTO.getLegalPersonId();
		}

		//对私实名认证 对公不做处理
		String verify = "0";
//		String verify = agent.getRecieveAccountType() == 1 ? "1" : "0";
		agent.setIsDefault(1);
		agent.setRecieveAccountType((byte)0);
		agent.setProfitRate(0);
		agentMapper.insertSelective(agent);

		PayUserAccounts payUserAccounts = PayUserAccounts.initialize(GroupId, UserId, CustomerName, CertNo, PayPwd,
				PwdAnswer, PwdQuest, Email, MobilePhone, null, OrgTranDateTime,verify);
		PayResult payResult = IPayAPI.individualUserAccounts(payUserAccounts);
		if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
			throw new ApplicationException(Rescode.FAIL,payResult.getMsgTxt());
		}
//		String CardDesc = agentInfoInDTO.getRecieveBank();
//		QueryCardCode queryCardCode=QueryCardCode.initialize(GroupId, agentInfoInDTO.getRecieveAccountNo());
//		PayCardCodeResult payCardCode=IPayAPI.queryCardCode(queryCardCode);
//		String accountType = "01";//表示借记卡
//		if(PayResult.SUCCESS.equals(payCardCode.getRespCode())){
//			if(payCardCode.getResult().get("CardType").contains("贷")){
//				accountType = "00";//表示贷记记卡
//			}
//		}
		//22表示对私 帮英航卡
//		PayBindBankCard bindbank = PayBindBankCard.initialize(UserId, PayPwd, SysTraceNum, GroupId, OrgTranDateTime,
//				OrgOrderNum, CardNum, CustomerName, accountType, MobilePhone, CertNo, issuerId, cardIntegral, CardDesc,
//				Integer.valueOf(verify),priOrpub);
//		PayResult bindResult = IPayAPI.userBindBankCard(bindbank);
//		if (!PayResult.SUCCESS.equals(bindResult.getRespCode())) {
//			throw new ApplicationException(Rescode.FAIL,bindResult.getMsgTxt());
//		}
		//设置费率
		Agent topAgent=agentMapper.selectMerchantCode(agent.getMerchantCode().substring(0,5));
		AgentRate agentRate=agentRateMapper.selectByPrimaryAgentId(topAgent.getId());
		//分润设置为平台设置 且为 2，3级代理商 需要设置好分润值
		if(agentRate!=null){
			Date date=new Date();
			if(agent.getAgentLevel().intValue()==2){
				agent.setPreprofitRate(agentRate.getSecondPurchaseRate());
				agent.setProfitRate(agentRate.getSecondFeeRate());
			}else if(agent.getAgentLevel().intValue()==3){
				agent.setPreprofitRate(agentRate.getThirdPurchaseRate());
				agent.setProfitRate(agentRate.getThirdFeeRate());
			}
			agent.setProfitUpdateTime(date);
			agent.setPreprofitValidTime(date);
			agent.setPreprofitUpdateTime(date);
			agent.setProfitValidTime(date);
			userbase.setStatus(UserStatus.Normal.getType());
			agent.setAgentStatus((byte) BizEnum.AgentStatus.Normal.getType());
		}else{
			userbase.setStatus(UserStatus.Stop.getType());
			agent.setAgentStatus((byte) BizEnum.AgentStatus.Stop.getType());
		}


		userbaseMapper.updateByPrimaryKey(userbase);
		agentMapper.updateByPrimaryKey(agent);




		//创建第二个默认的代理商
		Group group3 = groupMapper.selectByPrimaryKey(group.getId());
		String GroupId2 = group3.getPayGroupCode();
		String CustomerName2 = groupInDTO.getPrincipal();//姓名
//		String CustomerName2 = "高伟南";//姓名


		String MobilePhone2 = groupInDTO.getPrincipalMobile();
		String OrgTranDateTime2 = DateUtils.getDateTimeString("yyyyMMddHHmmss");
		// 生成UserBase
		String PayPwd2 = "111111";
		Userbase userbase2 = new Userbase();
		userbase2.setGmtCreate(new Date());
		userbase2.setGmtModified(new Date());

		String loginName2= StringUtil.getRandNumberStr(9)+"@epalmpay.cn";

		userbase2.setUsername(loginName2);
		userbase2.setPassword(new SimpleHash("SHA-1", loginName2, PayPwd2).toString());
		userbase2.setUserType(CommonEnum.UserType.Agents.getType());
		userbase2.setStatus(UserStatus.Stop.getType());
		userbase2.setGroupId(group.getId());
		userbase2.setRoleId("1");
		userbaseMapper.insertKey(userbase2);
		Agent agent2  = new Agent();
//		try {
//			PropertyCopyUtil.copyPropertiesExclude(agentInfoInDTO, agent,"agentId");
//		} catch (Exception e) {
//			e.printStackTrace();
//			throw new ApplicationException(Rescode.FAIL,"对象复制异常");
//		}


		agent2.setAddressProvince("上海市");
		agent2.setAddressCity("上海市");
		agent2.setAddressDistrict("浦东新区");
		agent2.setMemo("大商户代理");
		agent2.setBorcName("大商户代理");
		agent2.setLegalPersonIdurl("http://file.ebank007.com/file/sbs_test/group/addGroup/1522200863084[C@62849ff7.jpg");
		agent2.setBusinessLicense("123456");
		agent2.setLicensePicurl("http://file.ebank007.com/file/sbs_test/group/addGroup/1522200863084[C@62849ff7.jpg");
		agent2.setRecieveName("");
		agent2.setRecieveAccountNo("");


		agent2.setAgentType((byte)1);
		agent2.setPrincipal(groupInDTO.getPrincipal());
		agent2.setPrincipalMobile(groupInDTO.getPrincipalMobile());
		agent2.setLegalPersonName(groupInDTO.getPrincipal());
		agent2.setLegalPersonId(groupInDTO.getLegalPersonId());
		agent2.setMerchantName("默认代理二"+group.getId());
		agent2.setUserId(userbase2.getId());
		agent2.setGmtCreate(new Date());
		agent2.setCreator(groupInDTO.getMerchantName());
		agent2.setPacketStatus(true);
		agent2.setPayPassword(PayPwd2);
		agent2.setGroupId(group.getId());
		/*** 当前添加的用角色为渠道或者渠道的管理员**/
		agent2.setPrePurchaseMoney(0);
		String UserId2 = GroupId + UtilFun.formatNumber(agent2.getUserId(), 10);
		String PwdAnswer2 = "000000";
		String PwdQuest2 = "000000";
//		String Email = agentInfoInDTO.getUsername();
		String Email2 = loginName2;
//		String priOrpub2 = agent.getRecieveAccountType() == 1 ? "22" : "11";
		String priOrpub2 = "22";

		//大商户创建
		agent2.setAgentLevel(1);
		agent2.setParentId(null);
		String merchantCode2 = agentMapper.selectMaxMerchantCode(null, 5);
		if (StringUtils.isBlank(merchantCode2)) {
			//为空 从00001开始计算
			agent2.setMerchantCode("00001");
		} else {
			int merCode = Integer.parseInt(merchantCode2, 10);
			String merchantCode_ = String.format("%05d", merCode+1);
			agent2.setMerchantCode(merchantCode_);
		}

		String SysTraceNum2 = UtilFun.createRandomNum(10);
		String OrgOrderNum2 = DateUtils.getDateTimeString("yyyyMMddHHmmsss", new Date())+UtilFun.createRandomNum(5);
//		String CardNum = agentInfoInDTO.getRecieveAccountNo();
		String CardNum2 = groupInDTO.getLegalPersonId();
//		String issuerId2 = BizEnum.WithdrawBankList.fromType("360281199209198014").getName();
		agent2.setAgentStatus(Byte.valueOf(BizEnum.AgentStatus.Stop.getType()+""));
		agent2.setSource(BizEnum.AgentSource.Inside.getType());
		agent2.setPacketStatus(true);
		agent2.setPacketNum(UserId2);
		agent2.setSort(0);
		agent2.setProfitRate(0);

		agent2.setPrePurchaseStatus(0);
		agent2.setRecommendUrl(null);
		agent2.setRecommendLink(null);

		//身份证
		String CertNo2 =null;
		String cardIntegral2 = "000000000000";
		if (StringUtils.isNotBlank(groupInDTO.getLegalPersonId())) {
//		if (StringUtils.isNotBlank(agentInfoInDTO.getBankBranch())) {
			CertNo2 = groupInDTO.getLegalPersonId();
			agent2.setBankBranch(CertNo2);
		}else{
			CertNo2 =groupInDTO.getLegalPersonId();
//			CertNo = agentInfoInDTO.getLegalPersonId();
		}

		//对私实名认证 对公不做处理
//		String verify2 = agent.getRecieveAccountType() == 1 ? "1" : "0";
		String verify2 = "0";
		agent2.setRecieveAccountType((byte)0);
		agent2.setIsDefault(2);
		agentMapper.insertSelective(agent2);

		PayUserAccounts payUserAccounts2 = PayUserAccounts.initialize(GroupId2, UserId2, CustomerName2, CertNo2, PayPwd2,
				PwdAnswer2, PwdQuest2, Email2, MobilePhone2, null, OrgTranDateTime2,verify2);
		PayResult payResult2 = IPayAPI.individualUserAccounts(payUserAccounts2);
		if (!PayResult.SUCCESS.equals(payResult2.getRespCode())) {
			throw new ApplicationException(Rescode.FAIL,payResult2.getMsgTxt());
		}
//		String CardDesc = agentInfoInDTO.getRecieveBank();
//		QueryCardCode queryCardCode=QueryCardCode.initialize(GroupId, agentInfoInDTO.getRecieveAccountNo());
//		PayCardCodeResult payCardCode=IPayAPI.queryCardCode(queryCardCode);
//		String accountType = "01";//表示借记卡
//		if(PayResult.SUCCESS.equals(payCardCode.getRespCode())){
//			if(payCardCode.getResult().get("CardType").contains("贷")){
//				accountType = "00";//表示贷记记卡
//			}
//		}
		//22表示对私 帮英航卡
//		PayBindBankCard bindbank = PayBindBankCard.initialize(UserId, PayPwd, SysTraceNum, GroupId, OrgTranDateTime,
//				OrgOrderNum, CardNum, CustomerName, accountType, MobilePhone, CertNo, issuerId, cardIntegral, CardDesc,
//				Integer.valueOf(verify),priOrpub);
//		PayResult bindResult = IPayAPI.userBindBankCard(bindbank);
//		if (!PayResult.SUCCESS.equals(bindResult.getRespCode())) {
//			throw new ApplicationException(Rescode.FAIL,bindResult.getMsgTxt());
//		}
		//设置费率
		Agent topAgent2=agentMapper.selectMerchantCode(agent2.getMerchantCode().substring(0,5));
		AgentRate agentRate2=agentRateMapper.selectByPrimaryAgentId(topAgent2.getId());
		//分润设置为平台设置 且为 2，3级代理商 需要设置好分润值
		if(agentRate2!=null){
			Date date=new Date();
			if(agent2.getAgentLevel().intValue()==2){
				agent2.setPreprofitRate(agentRate2.getSecondPurchaseRate());
				agent2.setProfitRate(agentRate2.getSecondFeeRate());
			}else if(agent.getAgentLevel().intValue()==3){
				agent2.setPreprofitRate(agentRate2.getThirdPurchaseRate());
				agent2.setProfitRate(agentRate2.getThirdFeeRate());
			}
			agent2.setProfitUpdateTime(date);
			agent2.setPreprofitValidTime(date);
			agent2.setPreprofitUpdateTime(date);
			agent2.setProfitValidTime(date);
			userbase2.setStatus(UserStatus.Normal.getType());
			agent2.setAgentStatus((byte) BizEnum.AgentStatus.Normal.getType());
		}else{
			userbase2.setStatus(UserStatus.Stop.getType());
			agent2.setAgentStatus((byte) BizEnum.AgentStatus.Stop.getType());
		}


		userbaseMapper.updateByPrimaryKey(userbase2);
		agentMapper.updateByPrimaryKey(agent2);




		return group.getId();
	}

	public List<GroupOutDTO> getGroupIdAndName() throws Exception {
		List<GroupOutDTO> groupOutDTOList = new ArrayList<GroupOutDTO>();
		List<Group> groupList = groupMapper.getGroupIdAndName();
		for(int i = 0; i < groupList.size(); i++) {
			GroupOutDTO groupOutDTO = new GroupOutDTO();
			groupOutDTO.setGroupId(groupList.get(i).getId());
			groupOutDTO.setMerchantName(groupList.get(i).getMerchantName());
			groupOutDTOList.add(groupOutDTO);
		}
		return groupOutDTOList;
	}

	@Override
	public GroupOutDTO getGroupById(Long groupId) throws Exception {

		GroupOutDTO  groupOutDTO = new GroupOutDTO();
		Group group = groupMapper.selectByPrimaryKey(groupId);
		groupOutDTO.setMerchantName(group.getMerchantName());
		return groupOutDTO;
	}

	@Override
	public GroupOutDTO getGroupPhone(Long groupId) throws Exception {
		GroupOutDTO  groupOutDTO = new GroupOutDTO();
		Group group = groupMapper.selectByPrimaryKey(groupId);
		groupOutDTO.setPrincipalMobile(group.getPrincipalMobile()); 
		return groupOutDTO;
	}

	@Override
	public void saveGroupConfig(GroupWxconfigInDTO groupWxconfigInDTO) throws Exception {
		
		if(StringUtils.isNotBlank(groupWxconfigInDTO.getWxAppid())){
			GroupWxconfig groupWxconfig =groupWxconfigMapper.selectByWxAppid(groupWxconfigInDTO.getWxAppid());
		  if(groupWxconfig!=null){
			  throw new ApplicationException(Rescode.FAIL, "微信公众号已存在");
		  }
		}
		
		if(StringUtils.isNotBlank(groupWxconfigInDTO.getWxTxid())){
			GroupWxconfig groupWxconfig =groupWxconfigMapper.selectByTxidKey(groupWxconfigInDTO.getWxTxid());
		  if(groupWxconfig!=null){
			  throw new ApplicationException(Rescode.FAIL, "微信公众号已存在");
		  }
		}
		
		GroupWxconfig groupWxconfig=new GroupWxconfig();
		PropertyCopyUtil.copyPropertiesExclude(groupWxconfigInDTO,groupWxconfig);
		groupWxconfig.setGmtCreate(new Date());
		groupWxconfig.setGmtModified(new Date());
		groupWxconfig.setAccessTokenUpdatetime(null); 
		groupWxconfigMapper.insert(groupWxconfig);
	}




	@Override
	public void updateGroupConfig(GroupWxconfigInDTO groupWxconfigInDTO) throws Exception {
		GroupWxconfig groupWxconfig=groupWxconfigMapper.selectByGroupId(groupWxconfigInDTO.getGroupId());
		if(groupWxconfig!=null){
			PropertyCopyUtil.copyPropertiesExclude(groupWxconfigInDTO,groupWxconfig);
			groupWxconfigMapper.updateByPrimaryKey(groupWxconfig);
		}else{
			if(StringUtils.isNotBlank(groupWxconfigInDTO.getWxAppid())){
				GroupWxconfig tGroupWxconfig =groupWxconfigMapper.selectByWxAppid(groupWxconfigInDTO.getWxAppid());
			  if(tGroupWxconfig!=null){
				  throw new ApplicationException(Rescode.FAIL, "微信公众号已存在");
			  }
			}
			
			if(StringUtils.isNotBlank(groupWxconfigInDTO.getWxTxid())){
				GroupWxconfig tGroupWxconfig =groupWxconfigMapper.selectByTxidKey(groupWxconfigInDTO.getWxTxid());
			  if(tGroupWxconfig!=null){
				  throw new ApplicationException(Rescode.FAIL, "微信公众号已存在");
			  }
			}
			
			GroupWxconfig config=new  GroupWxconfig();
			PropertyCopyUtil.copyPropertiesExclude(groupWxconfigInDTO,config);
			config.setGmtCreate(new Date());
			config.setGmtModified(new Date());
			config.setAccessTokenUpdatetime(null); 
			groupWxconfigMapper.insert(config);
		}
		
	}

	@Override
	public GroupWxconfig selectGroupWxconfigId(Long groupId) throws Exception {
		GroupWxconfig groupWxconfig=groupWxconfigMapper.selectByGroupId(groupId);
		return groupWxconfig; 
		
	}

	@Override
	public GroupConfig selectGroupSysConfig(Long groupId) {
		
		return groupConfigMapper.getSystemParamsByGroupId(groupId) ;
	}

	@Override
	public Boolean selectGroupModel(Long groupId) {
		GroupModule groupModule=new GroupModule();
		groupModule.setGroupId(new Long(groupId).intValue());
		Byte moduleId=19;//分销商管理(勾选开通钱包) id
		groupModule.setModuleId(moduleId);
		GroupModule group=groupModuleMapper.selectModelIdToGroupId(groupModule);
		if(group==null){
			return false;
		}else{
			return true;
		}
	}

	@Override
	public Group selectGroupInfo(Long groupId) throws ApplicationException {
		Group group=groupMapper.selectInfo(groupId);
		if(group==null){
			throw new ApplicationException(Rescode.FAIL, "信息不存在");
		}
		return group;
	}

	@Override
	public GroupListOutDTO wxtemplateList(Long groupId,int type) throws ApplicationException {
		List<GroupWxtemplate> groupWxtemplateList=groupWxtemplateMapper.selectByGroupId(groupId, type);
		ArrayList<GroupWxtemplateOutDTO> groupWxtemplateOutDTO=new ArrayList<GroupWxtemplateOutDTO>();
		GroupListOutDTO groupListOutDTO=new GroupListOutDTO();
		for (GroupWxtemplate groupWxtemplate : groupWxtemplateList) {
			try {
				GroupWxtemplateOutDTO gr=new GroupWxtemplateOutDTO();
				PropertyCopyUtil.copyPropertiesExclude(groupWxtemplate,gr);
				groupWxtemplateOutDTO.add(gr);
			} catch (Exception e) {
				throw new ApplicationException(Rescode.FAIL,"对象属性复制异常");
			}
		}
		groupListOutDTO.setGroupWxtemplateList(groupWxtemplateOutDTO);
		return groupListOutDTO;
	}

	@Override
	public void saveWxtemplate(GroupWxtemplateInDTO groupWxtemplateInDTO) throws ApplicationException {
		GroupWxconfig groupWxconfig=groupWxconfigMapper.selectByGroupId(groupWxtemplateInDTO.getGroupId());
		if(groupWxconfig==null){
			throw new ApplicationException(Rescode.FAIL,"微信未配置");
		}
		String templateId=null;
		try {
			 wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(groupWxtemplateInDTO.getGroupId()));
			 templateId = this.wxService.getTemplateMsgService().addTemplate(groupWxtemplateInDTO.getTemplateType());
		} catch (WxErrorException e) {
			throw new ApplicationException(Rescode.FAIL,"微信模板消息接口调用失败");
		}
		WebTemplateType webTemplateType=BizEnum.WebTemplateType.fromType(groupWxtemplateInDTO.getTemplateType());
		GroupWxtemplate groupWxtemplate=new GroupWxtemplate();
		groupWxtemplate.setTemplateType(groupWxtemplateInDTO.getTemplateType()); 
		groupWxtemplate.setTemplateName(webTemplateType.getName()); 
		groupWxtemplate.setGmtCreate(new Date()); 
		groupWxtemplate.setType(groupWxtemplateInDTO.getType());
		groupWxtemplate.setContent(webTemplateType.getDesc());
		groupWxtemplate.setGroupId(groupWxtemplateInDTO.getGroupId());
		groupWxtemplate.setTemplateId(templateId);
		groupWxtemplateMapper.insert(groupWxtemplate);
	}
	

	@Override
	public Boolean deleteWxtemplate (GroupWxtemplateInDTO groupWxtemplateInDTO) throws ApplicationException {
		GroupWxtemplate groupWxtemplate=groupWxtemplateMapper.selectByPrimaryKey(groupWxtemplateInDTO.getId());
		try {
			wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(groupWxtemplateInDTO.getGroupId()));
			this.wxService.getTemplateMsgService().delPrivateTemplate(groupWxtemplate.getTemplateId());
			groupWxtemplateMapper.deleteByPrimaryKey(groupWxtemplateInDTO.getId());
		} catch (WxErrorException e) {
			throw new ApplicationException(Rescode.FAIL,"模板删除异常");
		}
		return true;
	}

	@Override
	public GroupWxtemplateOutDTO findTemplate(GroupWxtemplateInDTO groupWxtemplateInDTO) throws ApplicationException {
		if(Tools.isEmpty(groupWxtemplateInDTO.getTemplateType())||groupWxtemplateInDTO.getGroupId()==null){
			throw new ApplicationException(Rescode.FAIL,"参数错误");
		}
		GroupWxtemplateOutDTO templateOut=new GroupWxtemplateOutDTO();
		GroupWxtemplate templateIn=groupWxtemplateMapper.selectByTemplateTypeAndGroup(groupWxtemplateInDTO.getTemplateType(),groupWxtemplateInDTO.getGroupId());
		if(templateIn!=null){
			try {
				PropertyCopyUtil.copyPropertiesExclude(templateIn,templateOut);
			} catch (Exception e) {
				throw new ApplicationException(Rescode.FAIL,"对象属性复制异常");
			}
		}
		return templateOut;
	}

	@Override
	public Boolean resetPassword(UserInDTO userInDTO) throws ApplicationException {
		Userbase userbase=userbaseMapper.selectByPrimaryKey(userInDTO.getId());
		userbase.setPassword(new SimpleHash("SHA-1", userbase.getUsername(), userInDTO.getPassword()).toString());
		userbaseMapper.updateByPrimaryKey(userbase);
		return true;
	}
	
	@Override
	public BaseOutDTO updatePassword(UserInDTO userInDTO) throws ApplicationException {
		BaseOutDTO baseOutDTO=new BaseOutDTO();
		Userbase userbase=userbaseMapper.selectByPrimaryKey(userInDTO.getId());
		String passwd = new SimpleHash("SHA-1", userbase.getUsername(), userInDTO.getOldPassword()).toString();	//密码加密
		if(!userbase.getPassword().equals(passwd)){
			baseOutDTO.setErrorCode(Rescode.FAIL,"原密码错误");
		}else{
			userbase.setPassword(new SimpleHash("SHA-1", userbase.getUsername(), userInDTO.getPassword()).toString());
			userbaseMapper.updateByPrimaryKey(userbase);
			baseOutDTO.setErrorCode(Rescode.SUCCESS, "密码修改成功");
		}
		return baseOutDTO;
	}

	@Override
	public GroupPayconfigOutDTO selectPayconfigId(Long groupId) throws Exception {
		GroupPayconfig groupPayconfig=groupPayconfigMapper.selectGroupId(groupId);
		GroupPayconfigOutDTO groupPayconfigOutDTO=new GroupPayconfigOutDTO();
		if(groupPayconfig!=null){
			PropertyCopyUtil.copyPropertiesExclude(groupPayconfig,groupPayconfigOutDTO);
		}
		return groupPayconfigOutDTO;
	}

	
	@Override
	public void updateGroupPayconfig(GroupPayconfigInDTO groupPayconfigInDTO) throws Exception {
		GroupPayconfig groupPayconfig=groupPayconfigMapper.selectGroupId(groupPayconfigInDTO.getGroupId());
		if(groupPayconfig!=null){
			PropertyCopyUtil.copyPropertiesExclude(groupPayconfigInDTO,groupPayconfig);
			groupPayconfigMapper.updateByPrimaryKey(groupPayconfig);
		}else{ 
			GroupPayconfig groupPayconfig_=new  GroupPayconfig();
			PropertyCopyUtil.copyPropertiesExclude(groupPayconfigInDTO,groupPayconfig_);
			groupPayconfig_.setGmtCreate(new Date());
			groupPayconfig_.setGmtModified(new Date());
			groupPayconfigMapper.insert(groupPayconfig_);
		}
		
	}

	public Boolean hasPayGroupCode(GroupInDTO groupInDTO) throws Exception{
		Boolean result = Boolean.FALSE;
		if(groupMapper.selectPayGroupCodeCount(groupInDTO.getPayGroupCode())>0)
			throw new ApplicationException("商户机构号重复！");
		return result;
	}

	@Override
	public GroupListOutDTO wxMenuList(GroupWxmenuInfoInDTO groupWxmenuInfoInDTO) throws ApplicationException {
		GroupWxmenuInfo record=new GroupWxmenuInfo();
		record.setGroupId(groupWxmenuInfoInDTO.getGroupId()); 
		record.setParentWxmenuId(groupWxmenuInfoInDTO.getParentWxmenuId());
		List <GroupWxmenuInfo> groupWxmenuInfoList=groupWxmenuInfoMapper.selectListByGroupId(record);
		ArrayList<GroupWxmenuInfoOutDTO> groupWxtemplateOutDTO=new ArrayList<GroupWxmenuInfoOutDTO>();
		GroupListOutDTO groupListOutDTO=new GroupListOutDTO();
		for (GroupWxmenuInfo groupWxmenuInfo : groupWxmenuInfoList) {
			try {
				GroupWxmenuInfoOutDTO gr=new GroupWxmenuInfoOutDTO();
				PropertyCopyUtil.copyPropertiesExclude(groupWxmenuInfo,gr);
				groupWxtemplateOutDTO.add(gr);
			} catch (Exception e) {
				throw new ApplicationException(Rescode.FAIL,"对象属性复制异常");
			}
		}
		groupListOutDTO.setGroupWxmenuInfoOutDTO(groupWxtemplateOutDTO); 
		return groupListOutDTO;
	}

	@Override
	public void saveWxMenu(GroupWxmenuInfoInDTO groupWxmenuInfoInDTO) throws ApplicationException {
		GroupWxmenuInfo groupWxmenuInfo=new GroupWxmenuInfo();
		groupWxmenuInfo.setGmtCreate(new Date());
		groupWxmenuInfo.setGmtModified(new Date());
		groupWxmenuInfo.setGroupId(groupWxmenuInfoInDTO.getGroupId());
		groupWxmenuInfo.setMediaId(groupWxmenuInfoInDTO.getMediaId());
		groupWxmenuInfo.setMenuType(groupWxmenuInfoInDTO.getMenuType());
		groupWxmenuInfo.setName(groupWxmenuInfoInDTO.getName());
		groupWxmenuInfo.setParentWxmenuId(groupWxmenuInfoInDTO.getParentWxmenuId());
		groupWxmenuInfo.setSortNum(groupWxmenuInfoInDTO.getSortNum());
		groupWxmenuInfo.setUrl(groupWxmenuInfoInDTO.getUrl());
		groupWxmenuInfo.setWxMenuRecordId(null);
		groupWxmenuInfoMapper.insert(groupWxmenuInfo);
		
	}

	@Override
	public BaseOutDTO deleteWxMenu(GroupWxmenuInfoInDTO groupWxmenuInfoInDTO) throws ApplicationException {
		List <GroupWxmenuInfo> list=groupWxmenuInfoMapper.selectListByParentId(groupWxmenuInfoInDTO.getGroupId(),groupWxmenuInfoInDTO.getId());
		BaseOutDTO baseOutDTO=new BaseOutDTO();
		if(list.size()>0){
			baseOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "存在下级菜单,不能删除");
			return baseOutDTO;
		}
		try {
			int wxCount=groupWxmenuInfoMapper.deleteByPrimaryKey(groupWxmenuInfoInDTO.getId());
			if(wxCount==0){
				 baseOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "处理出现异常");
			}else{
				baseOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");
			}
		} catch (Exception e) {
			 e.printStackTrace();
			 baseOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "处理出现异常");
		}
		return baseOutDTO;
	}

	@Override
	public void updateWxMenu(GroupWxmenuInfoInDTO groupWxmenuInfoInDTO) throws ApplicationException {
		GroupWxmenuInfo groupWxmenuInfo=groupWxmenuInfoMapper.selectByPrimaryKey(groupWxmenuInfoInDTO.getId());
		if(groupWxmenuInfo!=null){
			groupWxmenuInfo.setGmtModified(new Date());
			groupWxmenuInfo.setMenuType(groupWxmenuInfoInDTO.getMenuType());
			groupWxmenuInfo.setName(groupWxmenuInfoInDTO.getName());
			groupWxmenuInfo.setSortNum(groupWxmenuInfoInDTO.getSortNum());
			groupWxmenuInfo.setUrl(groupWxmenuInfoInDTO.getUrl());
			groupWxmenuInfo.setWxMenuRecordId(null); 
			groupWxmenuInfoMapper.updateByPrimaryKey(groupWxmenuInfo);
		}else{
			throw new ApplicationException(Rescode.FAIL,"菜单信息不存在");
		}
	}

	@Override
	public void synchronizeWxMenu(GroupWxmenuInfoInDTO groupWxmenuInfoInDTO) throws ApplicationException {
		List <GroupWxmenuInfo> wxmenuInfoList=this.listWxMenuParentId(groupWxmenuInfoInDTO.getGroupId(),0L);
		WxMenu menu = new WxMenu();
		 for (GroupWxmenuInfo wxmenu : wxmenuInfoList) {
		    List <GroupWxmenuInfo> wxmenuInfoList1=this.listWxMenuParentId(groupWxmenuInfoInDTO.getGroupId(),wxmenu.getId());
			 if(wxmenuInfoList1.size()>0){
				 //有子菜单  第一级只需要显示名称即可
				 WxMenuButton button1 = new WxMenuButton();
				 button1.setName(wxmenu.getName());
				 menu.getButtons().add(button1);
				   for (GroupWxmenuInfo wx : wxmenuInfoList1) { 
					    WxMenuButton buttonOdd=button(wx);
					    button1.getSubButtons().add(buttonOdd);
				    } 
			 }else{
				 //无子菜单
				 WxMenuButton buttonOdd=button(wxmenu);
				 menu.getButtons().add(buttonOdd);
			 }
		} 
		 wxService.setWxMpConfigStorage(wxBaseService.getTokenByGroupId(groupWxmenuInfoInDTO.getGroupId()));
		try {
			this.wxService.getMenuService().menuCreate(menu);
		} catch (WxErrorException e) {
			e.printStackTrace();
			throw new ApplicationException(Rescode.FAIL,"菜单创建失败");
		}
		
	}
	
	
	public static WxMenuButton button(GroupWxmenuInfo wxmenu){
		WxMenuButton button = new WxMenuButton();
		if(wxmenu.getMenuType().equals(WxConsts.BUTTON_VIEW)){
			 button.setType(WxConsts.BUTTON_VIEW);
			 button.setName(wxmenu.getName());
			 button.setUrl(wxmenu.getUrl());
			 
		   }else if(wxmenu.getMenuType().equals(WxConsts.BUTTON_CLICK)){
			 button.setType(WxConsts.BUTTON_CLICK);
			 button.setName(wxmenu.getName());
			 button.setKey("key");
		 }
		return button;
	}
	
	public List<GroupWxmenuInfo> listWxMenuParentId(Long groupId,Long parentWxmenuId)  {
		List <GroupWxmenuInfo> list=groupWxmenuInfoMapper.selectListByParentId(groupId,parentWxmenuId);
		return list; 
	}

	@Override
	public GroupWxmenuInfoOutDTO findWxmenuId(GroupWxmenuInfoInDTO groupWxmenuInfoInDTO) throws ApplicationException {
		GroupWxmenuInfo groupWxmenuInfo=groupWxmenuInfoMapper.selectByPrimaryKey(groupWxmenuInfoInDTO.getId());
		if(groupWxmenuInfo!=null){
			GroupWxmenuInfoOutDTO groupWxmenuInfoOutDTO=new GroupWxmenuInfoOutDTO();
			try {
				PropertyCopyUtil.copyPropertiesExclude(groupWxmenuInfo,groupWxmenuInfoOutDTO);
			} catch (Exception e) {
				e.printStackTrace();
				throw new ApplicationException(Rescode.FAIL,"赋值异常");
			}
			return groupWxmenuInfoOutDTO;
		}else{
			return null;
		}
		
	}
	
	
	@Override
	public GroupWxmenuInfoOutDTO findParentWxmenuId(GroupWxmenuInfoInDTO groupWxmenuInfoInDTO) throws ApplicationException {
		GroupWxmenuInfo groupWxmenuInfo=groupWxmenuInfoMapper.findParentWxmenuId(groupWxmenuInfoInDTO.getId(),groupWxmenuInfoInDTO.getGroupId());
		if(groupWxmenuInfo!=null){
			GroupWxmenuInfoOutDTO groupWxmenuInfoOutDTO=new GroupWxmenuInfoOutDTO();
			try {
				PropertyCopyUtil.copyPropertiesExclude(groupWxmenuInfo,groupWxmenuInfoOutDTO);
			} catch (Exception e) {
				e.printStackTrace();
				throw new ApplicationException(Rescode.FAIL,"赋值异常");
			}
			return groupWxmenuInfoOutDTO;
		}else{
			return null;
		}
		
	}


	

	@Override
	public GroupWxtemplateListOutDTO findTempInfosList(Long groupId, Integer type) throws ApplicationException {
		GroupWxtemplateListOutDTO groupWxtemplateListOutDTO=new GroupWxtemplateListOutDTO();
		List<GroupWxtemplate> groupWxtemplateList=groupWxtemplateMapper.selectByGroupId(groupId, type);
		ArrayList<GroupWxtemplateOutDTO> groupWxtemplateOutDTO=new ArrayList<GroupWxtemplateOutDTO>();
			if(type.intValue()==0){
				Set<String> keyset=BizEnum.WebTemplateType.webTemplateType.keySet();
				for(String key :keyset){
					GroupWxtemplateOutDTO gr=new GroupWxtemplateOutDTO();
					for (GroupWxtemplate groupWxtemplate : groupWxtemplateList) {
						if(key.equalsIgnoreCase( groupWxtemplate.getTemplateType())){
							try {
								PropertyCopyUtil.copyPropertiesExclude(groupWxtemplate,gr);
							} catch (Exception e) {
								throw new ApplicationException(Rescode.FAIL,"对象属性复制异常");
							}
							break;
						}
					}
					if(gr.getId()==null){
						gr.setTemplateType(key);
						gr.setContent(BizEnum.WebTemplateType.webTemplateType.get(key).getDesc());
						gr.setTemplateName(BizEnum.WebTemplateType.webTemplateType.get(key).getName());
					}				
					groupWxtemplateOutDTO.add(gr);
				}
				
			}else{
				Set<String> keyset=BizEnum.SMSTemplateType.sMSTemplateType.keySet();
				for(String key :keyset){
					GroupWxtemplateOutDTO gr=new GroupWxtemplateOutDTO();
					for (GroupWxtemplate groupWxtemplate : groupWxtemplateList) {
						if(key.equalsIgnoreCase( groupWxtemplate.getTemplateType())){
							try {
								PropertyCopyUtil.copyPropertiesExclude(groupWxtemplate,gr);
							} catch (Exception e) {
								throw new ApplicationException(Rescode.FAIL,"对象属性复制异常");
							}
							break;
						}
					}
					if(gr.getId()==null){
						gr.setTemplateType(key);
						gr.setContent(BizEnum.SMSTemplateType.sMSTemplateType.get(key).getDesc());
						gr.setTemplateName(BizEnum.SMSTemplateType.sMSTemplateType.get(key).getName());
					}				
					groupWxtemplateOutDTO.add(gr);
				}
			}
			
		groupWxtemplateListOutDTO.setGroupWxtemplates(groupWxtemplateOutDTO);
		return groupWxtemplateListOutDTO;
	}

	@Override
	public GroupWxtemplateListOutDTO finishSaveTemplates(List<GroupWxtemplateInDTO> groupWxtemplateInsDTO) throws ApplicationException {
		GroupWxtemplateListOutDTO groupWxtemplateListOutDTO=new GroupWxtemplateListOutDTO();
		
		for(GroupWxtemplateInDTO  template:groupWxtemplateInsDTO){
			if(template.getId()!=null){
				GroupWxtemplate groupWxtemplate=groupWxtemplateMapper.selectByPrimaryKey(template.getId());
				groupWxtemplate.setGmtModified(new Date());
				groupWxtemplate.setTemplateId(template.getTemplateId());
				groupWxtemplateMapper.updateByPrimaryKey(groupWxtemplate);
			}else{
				GroupWxtemplate	groupWxtemplate=new GroupWxtemplate();				
				groupWxtemplate.setDefaultSelect(0);
				groupWxtemplate.setGmtCreate(new Date());
				groupWxtemplate.setGmtModified(new Date());
				groupWxtemplate.setGroupId(template.getGroupId());
				groupWxtemplate.setTemplateId(template.getTemplateId());
				if(template.getType().intValue()==1){
					SMSTemplateType sMSTemplateType=BizEnum.SMSTemplateType.fromType(template.getTemplateType());
					groupWxtemplate.setTemplateName(sMSTemplateType.getName()); 
					groupWxtemplate.setContent(sMSTemplateType.getDesc());
				}else{
					WebTemplateType webTemplateType=BizEnum.WebTemplateType.fromType(template.getTemplateType());
					groupWxtemplate.setTemplateName(webTemplateType.getName()); 
					groupWxtemplate.setContent(webTemplateType.getDesc());
				}
				
				groupWxtemplate.setTemplateType(template.getTemplateType());
				groupWxtemplate.setType(template.getType());			
				groupWxtemplateMapper.insert(groupWxtemplate);
			}
		}
		groupWxtemplateListOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");
		return groupWxtemplateListOutDTO;
	}

	@Override
	public GroupOutDTO getGroupByNamed(String merchantName) throws ApplicationException {
		GroupOutDTO  groupOutDTO = new GroupOutDTO();
		Group group = groupMapper.selectByMerchantName(merchantName);
		try {
			if(group!=null){
				PropertyCopyUtil.copyProperties(group, groupOutDTO);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return groupOutDTO;
	}
	public GroupOutDTO queryGroupProtocol(GroupInDTO groupInDTO) throws ApplicationException {
		GroupOutDTO groupOutDTO = new GroupOutDTO();
		Group group=groupMapper.queryGroupInfo(groupInDTO.getGroupId());
		if(group !=null){
			groupOutDTO.setContent(group.getContent());
		}
		Agent record = agentMapper.queryAroupProtocol(groupInDTO.getGroupId());
		if(record !=null){
			groupOutDTO.setContent2(record.getContent());
		}
		return groupOutDTO;
	}

	@Override
	public List<Map> getGroupTrade(Map<String, Object> param) {
		return groupMapper.getGroupTrade(param);
	}

	@Override
	public List<Map> getGroupTradeShop(Map<String, Object> param) {
		return groupMapper.getGroupTradeShop(param);
	}


	@Override
	public void editGroup(GroupInDTO groupInDTO) throws ApplicationException {
		Group group = new Group();
		group.setId(groupInDTO.getId());
		group.setAddress(groupInDTO.getAddress());
		group.setGmtModified(new Date());
		group.setMerchantName(groupInDTO.getMerchantName());
		group.setPrincipalMobile(groupInDTO.getPrincipalMobile());
		group.setServiceTelephone(groupInDTO.getServiceTelephone());
		group.setIcon(groupInDTO.getIcon());
		group.setWebsite(groupInDTO.getWebsite());
		groupMapper.updateByPrimaryKeySelective(group);
	}

	@Override
	public void saveGroupProfile(Map<String, Object> param) {
		GroupProfile groupProfile = new GroupProfile();
		if(param.get("extendprofilerate") != null) {
			groupProfile.setExtendProfilerate(Integer.parseInt(param.get("extendprofilerate").toString()));
		}
		if(param.get("zhangfuprofilerate") != null) {
			groupProfile.setZhangfuProfilerate(Integer.parseInt(param.get("zhangfuprofilerate").toString()));
		}
		
		if(param.get("platformprofilerate") != null) {
			groupProfile.setPlatformProfilerate(Integer.parseInt(param.get("platformprofilerate").toString()));
		}
		if(param.get("operatetype") != null) {
			groupProfile.setOperateType(Integer.parseInt(param.get("operatetype").toString()));
		}
//		if(param.get("operateprofilerate") != null) {
//			groupProfile.setOperateProfilerate(Integer.parseInt(param.get("operateprofilerate").toString()));
//		}
//		if(param.get("operateaccount") != null) {
//			groupProfile.setOperateaccount(param.get("operateaccount").toString());
//		}
		if(param.get("groupid") != null) {
			groupProfile.setGroupId(SysUtils.Object2Long(param.get("groupid")));
		}
		groupProfileMapper.insert(groupProfile);
	}

	@Override
	public GroupProfile selectProfileByGroupid(Long id) {
		return groupProfileMapper.selectProfileByGroupid(id);
	}

	@Override
	public void deleteGroupProfile(Map<String, Object> param) {
		groupProfileMapper.deleteByPrimaryKey(SysUtils.Object2Integer(param.get("id")));
	}

	@Override
	public void updateGroupProfileById(Map<String, Object> param) {
		GroupProfile groupProfile = new GroupProfile();
		if(param.get("extendprofilerate") != null) {
			groupProfile.setExtendProfilerate(Integer.parseInt(param.get("extendprofilerate").toString()));
		}
		if(param.get("zhangfuprofilerate") != null) {
			groupProfile.setZhangfuProfilerate(Integer.parseInt(param.get("zhangfuprofilerate").toString()));
		}
//		if(param.get("operateprofilerate") != null) {
//			groupProfile.setOperateProfilerate(Integer.parseInt(param.get("operateprofilerate").toString()));
//		}
		if(param.get("platformprofilerate") != null) {
			groupProfile.setPlatformProfilerate(Integer.parseInt(param.get("platformprofilerate").toString()));
		}
		if(param.get("operatetype") != null) {
			groupProfile.setOperateType(Integer.parseInt(param.get("operatetype").toString()));
		}
		if(param.get("operateaccount") != null) {
			groupProfile.setOperateAccount(param.get("operateaccount").toString());
		}
		groupProfile.setId(SysUtils.Object2Integer(param.get("id")));
		groupProfile.setGmtModified(new Date());
		groupProfileMapper.updateByPrimaryKeySelective(groupProfile);
	}

	@Override
	public void insertGroupPoster(Poster record) {
		groupPosterMapper.insert(record);
	}

	@Override
	public void updateGroupPoster(Poster record) {
		groupPosterMapper.updatePoster(record);
	}

	@Override
	public Poster selectPosterByGroupid(Poster record) {
		return groupPosterMapper.selectPosterByGroupid(record);
	}

	@Override
	public void saveGroupProtocol(GroupInDTO groupInDTO) throws ApplicationException {

		Group group = new Group();
		group.setId(groupInDTO.getId());
		group.setContent(groupInDTO.getContent());
		group.setGmtModified(new Date());
		groupMapper.updateByPrimaryKeySelective(group);


		List<Agent> agentList = agentMapper.getIdByGroupId(groupInDTO.getId());
		if(agentList.size()>0){

			for(Agent agent :agentList){
				Agent record = new Agent();
				record.setId(agent.getId());
				record.setContent(groupInDTO.getContent2());
				record.setGmtModified(new Date());
				agentMapper.updateByPrimaryKeySelective(record);
			}
		}
	}



	@Override
	public Response addAgent(String groupId, String principal,String legalPersonId, String principalMobile) throws ApplicationException {



		Map<String, Object> map = new HashMap<>();

		//创建第一个掌富账号
		Group group2 = groupMapper.selectByPrimaryKey(Long.parseLong(groupId));
		String GroupId = group2.getPayGroupCode();
//		String CustomerName = groupInDTO.getPrincipal();//姓名
		String CustomerName = "陈辉辉";//姓名


		String MobilePhone = "18706085592";
//		String MobilePhone = groupInDTO.getPrincipalMobile();
		String OrgTranDateTime = DateUtils.getDateTimeString("yyyyMMddHHmmss");
		// 生成UserBase
		String PayPwd = "111111";
		Userbase userbase = new Userbase();
		userbase.setGmtCreate(new Date());
		userbase.setGmtModified(new Date());

		String loginName= StringUtil.getRandNumberStr(9)+"@epalmpay.cn";

		userbase.setUsername(loginName);
		userbase.setPassword(new SimpleHash("SHA-1", loginName, PayPwd).toString());
		userbase.setUserType(CommonEnum.UserType.Agents.getType());
		userbase.setStatus(UserStatus.Stop.getType());
		userbase.setGroupId(group2.getId());
		userbase.setRoleId("1");
		userbaseMapper.insertKey(userbase);
		Agent agent  = new Agent();
//		try {
//			PropertyCopyUtil.copyPropertiesExclude(agentInfoInDTO, agent,"agentId");
//		} catch (Exception e) {
//			e.printStackTrace();
//			throw new ApplicationException(Rescode.FAIL,"对象复制异常");
//		}
		agent.setPrincipal("陈辉辉");
		agent.setPrincipalMobile("18706085592");
		agent.setLegalPersonName("陈辉辉");
		agent.setLegalPersonId("350725199302130019");
		agent.setMerchantName("默认代理一"+group2.getId());
		agent.setUserId(userbase.getId());
		agent.setGmtCreate(new Date());
		agent.setCreator("默认代理一"+group2.getId());
		agent.setPacketStatus(true);
		agent.setPayPassword(PayPwd);
		agent.setGroupId(group2.getId());
		/*** 当前添加的用角色为渠道或者渠道的管理员**/
		agent.setPrePurchaseMoney(0);
		String UserId = GroupId + UtilFun.formatNumber(agent.getUserId(), 10);
		String PwdAnswer = "000000";
		String PwdQuest = "000000";
//		String Email = agentInfoInDTO.getUsername();
		String Email = loginName;
//		String priOrpub = agent.getRecieveAccountType() == 1 ? "22" : "11";
		String priOrpub = "22";

		//大商户创建
		agent.setAgentLevel(1);
		agent.setParentId(null);
		String merchantCode = agentMapper.selectMaxMerchantCode(null, 5);
		if (StringUtils.isBlank(merchantCode)) {
			//为空 从00001开始计算
			agent.setMerchantCode("00001");
		} else {
			int merCode = Integer.parseInt(merchantCode, 10);
			String merchantCode_ = String.format("%05d", merCode+1);
			agent.setMerchantCode(merchantCode_);
		}

		String SysTraceNum = UtilFun.createRandomNum(10);
		String OrgOrderNum = DateUtils.getDateTimeString("yyyyMMddHHmmsss", new Date())+UtilFun.createRandomNum(5);
//		String CardNum = agentInfoInDTO.getRecieveAccountNo();
		String CardNum = "350725199302130019";
//		String issuerId = BizEnum.WithdrawBankList.fromType("360281199209198014").getName();
		agent.setAgentStatus(Byte.valueOf(BizEnum.AgentStatus.Stop.getType()+""));
		agent.setSource(BizEnum.AgentSource.Inside.getType());
		agent.setPacketStatus(true);
		agent.setPacketNum(UserId);
		agent.setSort(0);
//		agent.setRecieveAccountNo("216180100100068521");

		agent.setPrePurchaseStatus(0);
		agent.setRecommendUrl(null);
		agent.setRecommendLink(null);

		String cardIntegral = "000000000000";
		String CertNo="";
		if (StringUtils.isNotBlank("350725199302130019")) {
//		if (StringUtils.isNotBlank(agentInfoInDTO.getBankBranch())) {
			CertNo = "350725199302130019";
			agent.setBankBranch(CertNo);
		}else{
			CertNo = "350725199302130019";
//			CertNo = agentInfoInDTO.getLegalPersonId();
		}

		//对私实名认证 对公不做处理
		String verify = "0";
		agent.setRecieveAccountType((byte)0);
//		String verify = agent.getRecieveAccountType() == 1 ? "1" : "0";
		agent.setIsDefault(1);
		agent.setProfitRate(0);
		agentMapper.insertSelective(agent);

			PayUserAccounts payUserAccounts = PayUserAccounts.initialize(GroupId, UserId, CustomerName, CertNo, PayPwd,
				PwdAnswer, PwdQuest, Email, MobilePhone, null, OrgTranDateTime,verify);
		PayResult payResult = IPayAPI.individualUserAccounts(payUserAccounts);
		if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
			throw new ApplicationException(Rescode.FAIL,payResult.getMsgTxt());
		}
//		String CardDesc = agentInfoInDTO.getRecieveBank();
//		QueryCardCode queryCardCode=QueryCardCode.initialize(GroupId, agentInfoInDTO.getRecieveAccountNo());
//		PayCardCodeResult payCardCode=IPayAPI.queryCardCode(queryCardCode);
//		String accountType = "01";//表示借记卡
//		if(PayResult.SUCCESS.equals(payCardCode.getRespCode())){
//			if(payCardCode.getResult().get("CardType").contains("贷")){
//				accountType = "00";//表示贷记记卡
//			}
//		}
		//22表示对私 帮英航卡
//		PayBindBankCard bindbank = PayBindBankCard.initialize(UserId, PayPwd, SysTraceNum, GroupId, OrgTranDateTime,
//				OrgOrderNum, CardNum, CustomerName, accountType, MobilePhone, CertNo, issuerId, cardIntegral, CardDesc,
//				Integer.valueOf(verify),priOrpub);
//		PayResult bindResult = IPayAPI.userBindBankCard(bindbank);
//		if (!PayResult.SUCCESS.equals(bindResult.getRespCode())) {
//			throw new ApplicationException(Rescode.FAIL,bindResult.getMsgTxt());
//		}
		//设置费率
		Agent topAgent=agentMapper.selectMerchantCode(agent.getMerchantCode().substring(0,5));
		AgentRate agentRate=agentRateMapper.selectByPrimaryAgentId(topAgent.getId());
		//分润设置为平台设置 且为 2，3级代理商 需要设置好分润值
		if(agentRate!=null){
			Date date=new Date();
			if(agent.getAgentLevel().intValue()==2){
				agent.setPreprofitRate(agentRate.getSecondPurchaseRate());
				agent.setProfitRate(agentRate.getSecondFeeRate());
			}else if(agent.getAgentLevel().intValue()==3){
				agent.setPreprofitRate(agentRate.getThirdPurchaseRate());
				agent.setProfitRate(agentRate.getThirdFeeRate());
			}
			agent.setProfitUpdateTime(date);
			agent.setPreprofitValidTime(date);
			agent.setPreprofitUpdateTime(date);
			agent.setProfitValidTime(date);
			userbase.setStatus(UserStatus.Normal.getType());
			agent.setAgentStatus((byte) BizEnum.AgentStatus.Normal.getType());
		}else{
			userbase.setStatus(UserStatus.Stop.getType());
			agent.setAgentStatus((byte) BizEnum.AgentStatus.Stop.getType());
		}


		userbaseMapper.updateByPrimaryKey(userbase);
		agentMapper.updateByPrimaryKey(agent);




		//创建第二个默认的代理商
		Group group3 = groupMapper.selectByPrimaryKey(Long.parseLong(groupId));
		String GroupId2 = group3.getPayGroupCode();
		String CustomerName2 =principal;//姓名
//		String CustomerName2 = "高伟南";//姓名


		String MobilePhone2 = principalMobile;
		String OrgTranDateTime2 = DateUtils.getDateTimeString("yyyyMMddHHmmss");
		// 生成UserBase
		String PayPwd2 = "111111";
		Userbase userbase2 = new Userbase();
		userbase2.setGmtCreate(new Date());
		userbase2.setGmtModified(new Date());

		String loginName2= StringUtil.getRandNumberStr(9)+"@epalmpay.cn";

		userbase2.setUsername(loginName2);
		userbase2.setPassword(new SimpleHash("SHA-1", loginName2, PayPwd2).toString());
		userbase2.setUserType(CommonEnum.UserType.Agents.getType());
		userbase2.setStatus(UserStatus.Stop.getType());
		userbase2.setGroupId(group3.getId());
		userbase2.setRoleId("1");
		userbaseMapper.insertKey(userbase2);
		Agent agent2  = new Agent();
//		try {
//			PropertyCopyUtil.copyPropertiesExclude(agentInfoInDTO, agent,"agentId");
//		} catch (Exception e) {
//			e.printStackTrace();
//			throw new ApplicationException(Rescode.FAIL,"对象复制异常");
//		}
		agent2.setPrincipal(principal);
		agent2.setPrincipalMobile(principalMobile);
		agent2.setLegalPersonName(principal);
		agent2.setLegalPersonId(legalPersonId);

		agent2.setMerchantName("默认代理二"+group3.getId());
		agent2.setUserId(userbase2.getId());
		agent2.setGmtCreate(new Date());
		agent2.setCreator("默认代理二"+group3.getId());
		agent2.setPacketStatus(true);
		agent2.setPayPassword(PayPwd2);
		agent2.setGroupId(group3.getId());
		/*** 当前添加的用角色为渠道或者渠道的管理员**/
		agent2.setPrePurchaseMoney(0);
		String UserId2 = GroupId + UtilFun.formatNumber(agent2.getUserId(), 10);
		String PwdAnswer2 = "000000";
		String PwdQuest2 = "000000";
//		String Email = agentInfoInDTO.getUsername();
		String Email2 = loginName2;
//		String priOrpub2 = agent.getRecieveAccountType() == 1 ? "22" : "11";
		String priOrpub2 = "22";

		//大商户创建
		agent2.setAgentLevel(1);
		agent2.setParentId(null);
		String merchantCode2 = agentMapper.selectMaxMerchantCode(null, 5);
		if (StringUtils.isBlank(merchantCode2)) {
			//为空 从00001开始计算
			agent2.setMerchantCode("00001");
		} else {
			int merCode = Integer.parseInt(merchantCode2, 10);
			String merchantCode_ = String.format("%05d", merCode+1);
			agent2.setMerchantCode(merchantCode_);
		}

		String SysTraceNum2 = UtilFun.createRandomNum(10);
		String OrgOrderNum2 = DateUtils.getDateTimeString("yyyyMMddHHmmsss", new Date())+UtilFun.createRandomNum(5);
//		String CardNum = agentInfoInDTO.getRecieveAccountNo();
		String CardNum2 = legalPersonId;
//		String issuerId2 = BizEnum.WithdrawBankList.fromType("360281199209198014").getName();
		agent2.setAgentStatus(Byte.valueOf(BizEnum.AgentStatus.Stop.getType()+""));
		agent2.setSource(BizEnum.AgentSource.Inside.getType());
		agent2.setPacketStatus(true);
		agent2.setPacketNum(UserId2);
		agent2.setSort(0);

		agent2.setPrePurchaseStatus(0);
		agent2.setRecommendUrl(null);
		agent2.setRecommendLink(null);

		//身份证
		String CertNo2 =null;
		String cardIntegral2 = "000000000000";
		if (StringUtils.isNotBlank(legalPersonId)) {
//		if (StringUtils.isNotBlank(agentInfoInDTO.getBankBranch())) {
			CertNo2 = legalPersonId;
			agent2.setBankBranch(CertNo2);
		}else{
			CertNo2 =legalPersonId;
//			CertNo = agentInfoInDTO.getLegalPersonId();
		}

		//对私实名认证 对公不做处理
//		String verify2 = agent.getRecieveAccountType() == 1 ? "1" : "0";
		String verify2 = "0";
		agent2.setRecieveAccountType((byte)0);
		agent2.setIsDefault(2);
		agent2.setProfitRate(0);
		agentMapper.insertSelective(agent2);

		PayUserAccounts payUserAccounts2 = PayUserAccounts.initialize(GroupId2, UserId2, CustomerName2, CertNo2, PayPwd2,
				PwdAnswer2, PwdQuest2, Email2, MobilePhone2, null, OrgTranDateTime2,verify2);
		PayResult payResult2 = IPayAPI.individualUserAccounts(payUserAccounts2);
		if (!PayResult.SUCCESS.equals(payResult2.getRespCode())) {
			throw new ApplicationException(Rescode.FAIL,payResult2.getMsgTxt());
		}
//		String CardDesc = agentInfoInDTO.getRecieveBank();
//		QueryCardCode queryCardCode=QueryCardCode.initialize(GroupId, agentInfoInDTO.getRecieveAccountNo());
//		PayCardCodeResult payCardCode=IPayAPI.queryCardCode(queryCardCode);
//		String accountType = "01";//表示借记卡
//		if(PayResult.SUCCESS.equals(payCardCode.getRespCode())){
//			if(payCardCode.getResult().get("CardType").contains("贷")){
//				accountType = "00";//表示贷记记卡
//			}
//		}
		//22表示对私 帮英航卡
//		PayBindBankCard bindbank = PayBindBankCard.initialize(UserId, PayPwd, SysTraceNum, GroupId, OrgTranDateTime,
//				OrgOrderNum, CardNum, CustomerName, accountType, MobilePhone, CertNo, issuerId, cardIntegral, CardDesc,
//				Integer.valueOf(verify),priOrpub);
//		PayResult bindResult = IPayAPI.userBindBankCard(bindbank);
//		if (!PayResult.SUCCESS.equals(bindResult.getRespCode())) {
//			throw new ApplicationException(Rescode.FAIL,bindResult.getMsgTxt());
//		}
		//设置费率
		Agent topAgent2=agentMapper.selectMerchantCode(agent2.getMerchantCode().substring(0,5));
		AgentRate agentRate2=agentRateMapper.selectByPrimaryAgentId(topAgent2.getId());
		//分润设置为平台设置 且为 2，3级代理商 需要设置好分润值
		if(agentRate2!=null){
			Date date=new Date();
			if(agent2.getAgentLevel().intValue()==2){
				agent2.setPreprofitRate(agentRate2.getSecondPurchaseRate());
				agent2.setProfitRate(agentRate2.getSecondFeeRate());
			}else if(agent.getAgentLevel().intValue()==3){
				agent2.setPreprofitRate(agentRate2.getThirdPurchaseRate());
				agent2.setProfitRate(agentRate2.getThirdFeeRate());
			}
			agent2.setProfitUpdateTime(date);
			agent2.setPreprofitValidTime(date);
			agent2.setPreprofitUpdateTime(date);
			agent2.setProfitValidTime(date);
			userbase2.setStatus(UserStatus.Normal.getType());
			agent2.setAgentStatus((byte) BizEnum.AgentStatus.Normal.getType());
		}else{
			userbase2.setStatus(UserStatus.Stop.getType());
			agent2.setAgentStatus((byte) BizEnum.AgentStatus.Stop.getType());
		}


		userbaseMapper.updateByPrimaryKey(userbase2);
		agentMapper.updateByPrimaryKey(agent2);

		return Response.getSuccess(map);
	}

	@Override
	public GroupOutDTO goEditRate(GroupInDTO groupInDTO) throws ApplicationException {
		GroupOutDTO groupOutDTO = new GroupOutDTO();
		//查询是否有充值分润
		Group group = groupMapper.selectByPrimaryKey(groupInDTO.getGroupId());
		GroupProfile groupProfile =groupProfileMapper.queryGroupInfo(groupInDTO.getGroupId());
		if(group !=null && group.getIsRechange() !=null){
			groupOutDTO.setIsRechange(group.getIsRechange());
			groupOutDTO.setIsProfit(group.getIsProfit());
		}else{
			groupOutDTO.setIsRechange(null);
		}
		if(group !=null && group.getIsProfit() !=null){
			groupOutDTO.setIsProfit(group.getIsProfit());
		}else{
			groupOutDTO.setIsProfit(null);
		}
		if(groupProfile !=null){
			groupOutDTO.setOperateType(groupProfile.getOperateType());
			groupOutDTO.setZhangfuProfilerate(groupProfile.getZhangfuProfilerate());
			groupOutDTO.setRechargeProfilerate(groupProfile.getRechargeProfilerate());
		}else{
			groupOutDTO.setOperateType(null);
			groupOutDTO.setZhangfuProfilerate(null);
			groupOutDTO.setRechargeProfilerate(null);
		}

		return groupOutDTO;
	}

	@Override
	public void editGroupInfo(GroupInDTO groupInDTO) throws ApplicationException {
		Group group=new Group();
		group.setId(groupInDTO.getGroupId());
		group.setIsRechange(groupInDTO.getIsRechange());
		group.setIsProfit(groupInDTO.getIsProfit());
		group.setGmtModified(new Date());
		groupMapper.updateByPrimaryKeySelective(group);

		GroupProfile groupProfile = new GroupProfile();
		groupProfile.setOperateType(groupInDTO.getOperateType());
		groupProfile.setZhangfuProfilerate(groupInDTO.getZhangfuProfilerate());
		groupProfile.setGroupId(groupInDTO.getGroupId());
		groupProfile.setRechargeProfilerate(groupInDTO.getRechargeProfilerate());
		groupProfileMapper.updateGroupInfo(groupProfile);


	}


}
